﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options => 
                {
                    options.TokenValidationParameters = new()
                    {
                        //NameClaimType = "",
                        //RoleClaimType = "",

                        //是否验证Issuer
                        ValidateIssuer = true,
                        //是否验证Audience
                        ValidateAudience = true,
                        //是否验证失效时间
                        ValidateLifetime = true,
                        //是否验证SecurityKey
                        ValidateIssuerSigningKey = true,
                        //Audience
                        ValidAudience = "MDCClient",
                        //Issuer，这两项和签发jwt的设置一致
                        ValidIssuer = "MDCServer",
                        //SecurityKey
                        IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("KKqUZx15DF2y01rPNaPOYr4doES59Mbu"))
                    };
                });

builder.Services.AddAuthorization(options =>
{
    //Claim中携带Admin即可通过认证
    //options.AddPolicy("Admin", policy =>policy.RequireClaim("Admin"));

    //Role角色为Admin通过认证
    options.AddPolicy("Admin", policy => policy.RequireRole("Admin"));
});


// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

//app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

//启用跨域
app.UseCors(builder =>
{
    builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
});

//启用授权
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
